package org.yxing.palpalgps.adapter;

import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.domain.AsyncImageLoader;
import org.yxing.palpalgps.domain.AsyncImageLoader.ImageCallback;
import org.yxing.palpalgps.utils.Helper;
import org.yxing.palpalgps.widget.AsyncImageView;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class InterestAdapter extends JSONArrayAdapter {
    private static final String TAG = InterestAdapter.class.getSimpleName();
    
    private Context mContext;
    
    private String imageUrl;
    
    public InterestAdapter(Context context) {
        mContext = context;
        imageUrl = "http://" + Helper.getHost() + "/images/interest/";
    }

    public long getItemId(int position) {
        JSONObject item = getItem(position);
        int id = 0;
        try {
            id = item.getInt("iid");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return id;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
//        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.group_item, null);
//        }
        AsyncImageView iconImageView = (AsyncImageView) convertView.findViewById(R.id.iconImageView);
        iconImageView.setImageDrawable(null);
        TextView nameTextView = (TextView) convertView.findViewById(R.id.nameTextView);
        
        JSONObject obj = getItem(position);
        if (obj != null) {
            try {
                String pid = obj.getString("parent");
                String name = obj.getString("name");
                //set image
                iconImageView.setUrl(getImageSrc(pid));
                //set name
                nameTextView.setText(name);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        
        
        return convertView;
    }
    
    /**
     * image callback
     */
    private ImageCallback mImageCallBack = new ImageCallback() {
        
        public void imageLoaded(Drawable imageDrawable, ImageView imageView,
                String imageUrl) {
            imageView.setImageDrawable(imageDrawable);
        }
    };
    
    public String getImageSrc(String id) {
        return imageUrl +  id + ".png";
    }
}
